package com.cdream.basic.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class HttpUtilExample {
    private static final MediaType JSON = MediaType.parse("application/json;charset=UTF-8");

    public static String sendRequest(String url, Map<String, Object> param, Object data, Method method) {

        // 1. 处理请求的params[hutool 居然没给提供....]
        url = addParamToUrl(url, param);
        // 2. 处理请求头
        RequestBody body = null;
        if (method != Method.GET) {
            body = RequestBody.create(JSON, JSONUtil.toJsonStr(Optional.ofNullable(data).orElse(MapUtil.newHashMap())));
        }
        Request request = new Request.Builder()
                .url(url)
                .method(method.name(), body)
                .header("Accept", "application/hal+json;charset=UTF-8")
                .header("Accept-Language", "zh-CN")
                .header("Content-Type", "application/json;charset=UTF-8")
                .build();
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(3, TimeUnit.MINUTES).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
        }
        return StrUtil.EMPTY;
    }

    private static String addParamToUrl(String url, Map<String, Object> param) {
        url += param.entrySet().stream().map(a -> a.getKey() + "=" + a.getValue())
                .collect(Collectors.joining("&", "?", ""));
        return url;
    }

    public static void main(String[] args) {
        Map<String, Object> param = MapUtil.<String, Object>builder()
                .put("access_token", "YWY5YWI5NDJiOWY1MTIxNjEyYzY3ODNjNjE4MmUzZWY2Y2FmYjQ0YSZ0PTE1OTY0MTU4JmE9NTAwMDAwMTAyJnU9MjUwODM3MjkxNTY2ODMzNjY0JnM9MTMwMDAwMDQ3MiZJPTE")
                .put("resourceId", "242643409171808256")
                .build();
        String baseUrl = "https://api.qidian.qq.com/cgi-bin/b2b/api/salesOrders/attachments/254413615304945664";
        String s = sendRequest(baseUrl, param, null, Method.DELETE);

    }
}
